/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.rpp.core;

import com.rpp.servlet.HttpServlet;
import com.rpp.servlet.RequestMapping;
import com.rpp.servlet.RequestProcessor;
import com.rpp.utils.ResourceUtil;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Author rpp
 * @Date 2020/7/22 11:42 下午
 */
public final class Mapper {

    private StandardService service;

    volatile List<MappedHost> hosts = new ArrayList<>();

    /**
     * Default host
     */
    public String defaultHostName = "localhost";
    public String defaultAppBase = "webApps";
    private volatile MappedHost defaultHost = new MappedHost(defaultHostName, defaultAppBase);

    /**
     * 线程池
     */
    private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            10,
            50,
            100L,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(50),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy()
    );

    public Mapper(StandardService service) {
        this.service = service;
    }

    public static final class MappedHost {

        private String name;
        private String appBase;

        private MappedContext defaultContext;

        public List<MappedContext> contexts = new ArrayList<>();

        public MappedHost(String name, String appBase) {
            this.name = name;
            this.appBase = appBase;
            this.defaultContext = new MappedContext(appBase, "/");
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getAppBase() {
            return appBase;
        }

        public void setAppBase(String appBase) {
            this.appBase = appBase;
        }

        public void addContext(MappedContext context) {
            contexts.add(context);
        }

        public List<MappedContext> getContexts() {
            return contexts;
        }

        public MappedContext getDefaultContext() {
            return defaultContext;
        }
    }

    public void addHost(String name, String appBase) {
        hosts.add(new MappedHost(name, appBase));
    }

    public MappedHost findHost(String hostName) {
        for (MappedHost host : hosts) {
            if (host.getName().endsWith(hostName)) {
                return host;
            }
        }
        return null;
    }

    public static final class MappedContext {

        private String docBase;
        private String path;

        private MappedWrapper defaultWrapper = null;

        private MappedWrapper wrapper;

        public MappedContext(String docBase, String path) {
            this.docBase = docBase;
            this.path = path;
        }

        public String getDocBase() {
            return docBase;
        }

        public void setDocBase(String docBase) {
            this.docBase = docBase;
        }

        public String getPath() {
            return path;
        }

        public void setPath(String path) {
            this.path = path;
        }

        public MappedWrapper getDefaultWrapper() {
            return defaultWrapper;
        }

        public void setDefaultWrapper(MappedWrapper defaultWrapper) {
            this.defaultWrapper = defaultWrapper;
        }

        public MappedWrapper getWrapper() {
            return wrapper;
        }

        public void setWrapper(MappedWrapper wrapper) {
            this.wrapper = wrapper;
        }
    }

    public void addContext(String hostName, String appBase, String docBase, String path) {
        MappedHost host = findHost(hostName);
        if (null == docBase || null == path) {
            host.defaultContext = new MappedContext(appBase, "/");
        } else {
            host.addContext(new MappedContext(docBase, path));
        }
    }

    public static class MappedWrapper {

        private Map<String, HttpServlet> servletMap = new HashMap();

        public void addServlet(String url, HttpServlet servlet) {
            servletMap.put(url, servlet);
        }

        public void setServletMap(Map<String, HttpServlet> servletMap) {
            this.servletMap = servletMap;
        }

        public Map<String, HttpServlet> getServletMap() {
            return servletMap;
        }
    }

    /**
     * 初始化wapper
     */
    public void initWapper() {
        //遍历host,初始化contexts
        for (MappedHost host : hosts) {
            List<MappedContext> contexts = host.getContexts();

            //
            if (null == contexts || contexts.size() == 0) {
                //  /Users/webApps
                String appBase = host.getAppBase();

                //如果context为空，根据appBase路径遍历项目创建context
                for (File file : new File(appBase).listFiles()) {
                    if (file.isFile()) {
                        continue;
                    }
                    //创建context, /Users/webApps/demo1
                    MappedContext context = new MappedContext(host.getAppBase(), "/" + file.getName());
                    host.addContext(context);
                    //创建wrapper,封装请求映射信息
                    MappedWrapper wrapper = createWrapper(file);
                    context.setWrapper(wrapper);
                }
            } else {
                for (MappedContext context : contexts) {
                    String docBase = context.getDocBase();

                    for (File file : new File(docBase).listFiles()) {
                        if (file.isFile()) {
                            continue;
                        }
                        MappedWrapper wrapper = createWrapper(file);
                        context.setWrapper(wrapper);
                    }
                }
            }

        }
    }

    /**
     * 创建wrapper,封装请求映射信息
     *
     * @param root /Users/webApps/demo1
     * @return
     */
    private MappedWrapper createWrapper(File root) {
        try {
            File[] files = root.listFiles();
            for (File file : files) {
                if (file.isFile() && file.getName().equals("web.xml")) {
                    List<RequestMapping> list = ResourceUtil.loadServlet(file, root.getAbsolutePath());

                    MappedWrapper wrapper = new MappedWrapper();
                    //url :  /demo1/rpp1
                    for (RequestMapping requestMapping : list) {
                        wrapper.addServlet("/" + root.getName() + requestMapping.getUrl(), requestMapping.getServlet());
                    }
                    return wrapper;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 初始化默认的Wapper  "http://localhost:8080/index.html"
     */
    public void initDefaultWapper() {
        for (MappedHost host : hosts) {
            MappedContext context = host.getDefaultContext();
            MappedWrapper wrapper = createDefaultWrapper();
            context.setWrapper(wrapper);
        }
    }

    /**
     * 加载解析当前项目web.xml，初始化默认Servlet
     */
    private MappedWrapper createDefaultWrapper() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("web.xml");

        MappedWrapper wrapper = new MappedWrapper();
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                // <servlet-name>rpp</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>com.rpp.servlet.MyServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();
                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /rpp
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                wrapper.addServlet(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return wrapper;
    }

    public void start() throws Exception {

        List<Connector> connectors = service.getConnectors();

        //遍历connector，监听不同端口
        for (Connector connector : connectors) {

            int port = connector.getPort();

            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("=====>>>Minicat start on port：" + port);

            /**
             * 使用线程池
             */
            while (true) {
                Socket socket = serverSocket.accept();
                RequestProcessor requestProcessor = new RequestProcessor(socket, port, this);
                threadPoolExecutor.execute(requestProcessor);
            }
        }
    }
}
